#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <iostream>
#include <math.h>

using namespace std;
using namespace cv;

double GetDistance (Point p_a, Point p_b)
{
    double distance;
    distance =  powf((p_a.x - p_b.x), 2 ) + powf((p_a.y-p_b.y), 2);
    distance = sqrtf (distance);

    return distance;
}

int main()
{
    Mat frame;
    VideoCapture capture("1.avi");
    if (!capture.isOpened())
    {
        cout << "can't open the video" << endl;
        return -1;
    }

    capture >> frame;
    Mat fr2 = frame.clone();

    while (capture.read(frame))
    {

        vector<Mat> img_channels;
        split(frame, img_channels);
        Mat mid_image = img_channels.at(0) - img_channels.at(2);
        threshold(mid_image, mid_image, 80, 255, THRESH_BINARY);
        
        Mat element = getStructuringElement(MORPH_RECT, Size(1,1));
        Mat ele1 = getStructuringElement(MORPH_RECT, Size(5, 5));
        Mat ele2 = getStructuringElement(MORPH_RECT, Size(7,7));
        dilate(mid_image, mid_image, ele1);
        morphologyEx(mid_image, mid_image, MORPH_OPEN, element);
        floodFill(mid_image, Point(0,0), Scalar(255));
        morphologyEx(mid_image, mid_image, MORPH_CLOSE, ele1);

        vector<vector<Point>> contours;
        vector<Vec4i> hierachy;
        findContours(mid_image, contours, hierachy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);
        RotatedRect rec;
        bool findTarget = 0;
        int area[25] = {0};

        if( hierachy.size())
        {
            for(int i = 0; i>=0; i=hierachy[i][0])
            {
                if(hierachy[i][2]>0)
                {
                    RotatedRect rec_2 = minAreaRect(contours[hierachy[i][2]]);
                    Point2f P[4];
                    rec_2.points(P);
                    const float max_hwratio = 0.7;
                    const float min_hwratio = 0.3;
                    const float max_area =  2000;
                    const float min_area = 300;
                    float width = rec_2.size.width;
                    float height = rec_2.size.height;
                    if(height>width)
                    swap(height, width);
                    float area = width*height;
                    if (area>max_area||area<min_area||height/width>max_hwratio||height/width<min_hwratio)
                    {
                        continue;
                    }
                    Point center = rec_2.center;
                    circle( frame, center, 1, Scalar( 0, 0, 255), 1);
                    for(int j = 0; j<4; ++j)
                    {
                        line( frame, P[j], P[(j+1)%4], Scalar(0, 255, 0), 3);
                    }
                }
            }
        }
        imshow("2", frame);
        if (waitKey(30) == 32)
        {
            if (waitKey(0) == 32)
            {
                break;
            }
        }
    }

    return 0;
}